import os
import tkinter as tk
from tkinter import Canvas, Scrollbar, HORIZONTAL, Frame, messagebox
from CheckTextWidgets import CheckTextWidgets
import json
import subprocess
import threading


def center_window(window, width=900, height=600):
    # 获取屏幕宽度和高度
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()

    # 计算窗口的x和y坐标以使其居中
    x = (screen_width // 2) - (width // 2)
    y = (screen_height // 2) - (height // 2)

    # 设置窗口的位置
    window.geometry(f"{width}x{height}+{int(x)}+{int(y)}")


if __name__ == "__main__":
    root = tk.Tk()
    root.title("系统环境变量PATH管理工具 V1.03")
    center_window(root)
    root.resizable(False, False)

    # 初始化基本控件
    LabelFrame = tk.LabelFrame(root, text="备选路径", width=800, height=400)
    LabelFrame.pack(side="left", fill='y', padx=10, pady=10)

    btn_ReadCFG = tk.Button(root, text="读取配置", width=8)
    btn_ReadCFG.pack(pady=20)
    btn_ReadCFG.bind("<Button-1>", lambda event: read_cfg())

    btn_SaveCFG = tk.Button(root, text="保存配置", width=8)
    btn_SaveCFG.pack()
    btn_SaveCFG.bind("<Button-1>", lambda event: run_threading())

    btn_NewLine = tk.Button(root, text="添加一行", width=8)
    btn_NewLine.pack(side="bottom", pady=15)
    # btn_NewLine.bind("<Button-1>", lambda event: print("添加一行"))
    btn_NewLine.bind("<Button-1>", lambda event: ct1.add_widgets())

    btn_SelALL = tk.Button(root, text="全  选", width=8)
    btn_SelALL.pack(side="bottom", pady=15)
    btn_SelALL.bind("<Button-1>", lambda event: setall())

    btn_SelNotAll = tk.Button(root, text="全取消", width=8)
    btn_SelNotAll.pack(side="bottom", pady=15)
    btn_SelNotAll.bind("<Button-1>", lambda event: setnotall())

    # 创建一个Canvas和一个Scrollbar
    canvas = tk.Canvas(LabelFrame, width=780, borderwidth=0)
    scrollbar = tk.Scrollbar(LabelFrame, command=canvas.yview)
    # 布局Canvas和Scrollbar
    canvas.pack(side='left', fill='both', expand=True)
    scrollbar.pack(side='right', fill='y')

    frame = tk.Frame(canvas)
    frame.config(width=800)
    canvas.create_window((0, 0), window=frame, anchor='nw')
    # 更新Canvas的滚动区域

    def update_scrollregion(event):
        canvas.configure(scrollregion=canvas.bbox('all'))

    frame.bind('<Configure>', update_scrollregion)

    # 设置Scrollbar和Canvas的滚动功能
    scrollbar.config(command=canvas.yview)
    canvas.config(yscrollcommand=scrollbar.set)

    def on_mousewheel(event):
        # 获取鼠标滚轮滚动的方向（向上或向下）
        num = 0
        if event.delta > 0:
            num = -1  # 向上滚动，减小yview
        else:
            num = 1   # 向下滚动，增大yview

        # 更新Canvas的yview
        canvas.yview_scroll(num, "units")

    canvas.bind('<Configure>', lambda e: canvas.config(
        scrollregion=canvas.bbox("all")))
    canvas.bind_all("<MouseWheel>", on_mousewheel)

    # 实例化CheckTextWidgets
    ct1 = CheckTextWidgets(frame, check_var=False, text="", width=67)
    ct1.pack()

    # 读取配置
    def read_cfg():
        if not os.path.isfile('path_data.json'):
            messagebox.showinfo("提示", "无配置文件")
            return
        #  读取json文件
        with open('path_data.json', 'r', encoding='utf-8') as file:
            json_data = json.load(file)
        # 获取数据
        activate_list = json_data["activate"]
        deactivate_list = json_data["deactivate"]
        # 判断数据是否为空
        if len(activate_list) == 0 and len(deactivate_list) == 0:
            print("无配置")
            return
        else:
            # 清空ct1
            for i in range(len(ct1.widget_stact)-1):
                ct1.sub_widgets()
            # 添加两类数据
            for j in range(len(activate_list)):
                ct1.add_widgets(check_var=True, text=activate_list[j])
            for i in range(len(deactivate_list)):
                ct1.add_widgets(check_var=False, text=deactivate_list[i])
            # 删除第一行
            ct1.sub_widgets_for_index(0)

    # def setx_work(new_path):
    #     subprocess.run(
    #         args=["setx", "PATH", new_path, "/m"], check=True)
    #     messagebox.showinfo("提示", "设置成功")
    def run_threading():
        t1 = threading.Thread(target=save_cfg, name="Thread-1")
        t1.start()

    def save_cfg():
        new_dict = {}
        new_activate_list = []
        new_deactivate_list = []
        new_path = ""
        check = ct1.get_check_text()
        for i in range(len(check)):
            # print(check[i].check_var)
            if check[i].check_var == True and check[i].text != "":
                new_path += check[i].text + ";"
                new_activate_list.append(check[i].text)
            if check[i].check_var == False and check[i].text != "":
                new_deactivate_list.append(check[i].text)

        # print(new_path)
        user_env_var = "PATH"
        user_env_value = new_path
        # subprocess.run(
        #     args=["setx", user_env_var, user_env_value, "/m"], check=True)

        subprocess.run(
            args=["setx", user_env_var, user_env_value, "/m"], check=True, creationflags=subprocess.CREATE_NO_WINDOW)

        new_dict["activate"] = new_activate_list
        new_dict["deactivate"] = new_deactivate_list

        # 写入JSON文件
        with open('path_data.json', 'w', encoding='utf-8') as f:
            json.dump(new_dict, f, ensure_ascii=False, indent=4)

        messagebox.showinfo("提示", "设置成功")

    def setall():
        for i in range(len(ct1.widget_stact)):
            ct1.set_check_all(True)

    def setnotall():
        for i in range(len(ct1.widget_stact)):
            ct1.set_check_all(False)

    read_cfg()

    root.mainloop()
